package org.micro.rbac.util;

import lombok.extern.slf4j.Slf4j;

/**
 * 分布式ID工具类 16位
 *
 * @author hongsir
 * @since 2024/6/6
 **/
@Slf4j
public class IdUtil {
    private static final long START_TIMESTAMP = 1704038400000L;
    private static final long WORKER_ID_BITS = 5L;
    private static final long SEQUENCE_BITS = 8L;
    private final long workerId;
    private long sequence = 0L;
    private long lastTimestamp = -1L;

    public IdUtil(long workerId) {
        this.workerId = workerId;
    }

    public synchronized long nextId() {
        long timestamp = System.currentTimeMillis();

        if (timestamp < lastTimestamp) {
            throw new RuntimeException("Clock moved backwards. Refusing to generate id");
        }

        if (timestamp == lastTimestamp) {
            sequence = (sequence + 1) & ((1 << SEQUENCE_BITS) - 1);
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        return ((timestamp - START_TIMESTAMP) << (WORKER_ID_BITS + SEQUENCE_BITS))
                | (this.workerId << SEQUENCE_BITS)
                | sequence;
    }

    private long tilNextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }

}
